package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author ：sean
 * @date ：Created in 2022/5/18
 * @description ：全局异常处理类，通知类
 * @version: 1.0
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {
	// 异常类,捕获所有数据库的异常,只捕获SQL
	@ExceptionHandler(SQLException.class)
	public R<String> handlerSQLException(SQLException exception){
		String exMessage = exception.getMessage();
		log.error("[发生数据库异常],{}",exMessage);
		if(exMessage.contains("Duplicate entry")){
			// Duplicate entry 'zhaoliu32' for key 'idx_username'
			String[] split = exMessage.split(" ");
			String msg = split[2] + "已存在";
			return R.error("数据库异常,不允许数据重复,"+msg);
		}else if(exMessage.contains("Data truncation")){
			return R.error("数据库异常,数据太长");
		}else {
			return R.error("未知的数据库异常");
		}
	}
	// 捕获自己定义的CustomException
	@ExceptionHandler(CustomException.class)
	public R<String> handlerRuntimeException(CustomException exception){
		String exMessage = exception.getMessage();
		log.error("[发生业务异常],{}",exMessage);
		return R.error(exMessage);
	}
}
